package com.neusoft.neuiotms.dcam.fixed.converter;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.ProductDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Product;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetTypeRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.ProductRepository;
import com.neusoft.neuiotms.dcam.fixed.vo.ProductImportVO;

@Component
public class ProductConverter extends AbstractConverter<Product, ProductDTO> {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private AssetTypeRepository assetTypeRepository;

    @Override
    public Product toModel(final ProductDTO dto) {
        final Product model;
        if (dto.isNew()) {
            model = new Product();
        } else {
            model = this.productRepository.getOne(dto.getId());
        }

        model.setName(dto.getName());
        model.setSpecification(dto.getSpecification());
        model.setMeasureUnit(dto.getMeasureUnit());
        model.setMoney(dto.getMoney());
        model.setUpdateTime(new Date());
        model.setBelongs(dto.getBelongs());
        model.setBrand(dto.getBrand());
        if (dto.getAssetTypeId() != null) {
            model.setAssetType(this.assetTypeRepository.getOne(dto.getAssetTypeId()));
        }
        if (dto.getAssetTypeCode() != null) {
            model.setAssetType(this.assetTypeRepository.findByCode(dto.getAssetTypeCode()));
        }
        return model;
    }

    @Override
    public ProductDTO toDTO(final Product model, final boolean forListView) {
        final ProductDTO dto = new ProductDTO();

        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setSpecification(model.getSpecification());
        dto.setMeasureUnit(model.getMeasureUnit());
        dto.setMoney(model.getMoney());
        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setBelongs(model.getBelongs());
        dto.setBrand(model.getBrand());
        if (model.getAssetType() != null) {
            dto.setAssetTypeId(model.getAssetType().getId());
            dto.setAssetTypeName(model.getAssetType().getName());
            dto.setAssetTypeCode(model.getAssetType().getCode());
        }
        return dto;
    }

    public Product toModel(final ProductImportVO p) {
        final Product model = new Product();
        model.setName(p.getName());
        model.setSpecification(p.getSpecification());
        //        model.setMeasureUnit(p.getMeasureUnit());
        model.setMoney(p.getMoney());
        model.setUpdateTime(new Date());
        return model;
    }

}
